<template>
  <div class="archive-approval">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">归档审批</h1>
          <p class="page-subtitle">审核已结案件的归档申请</p>
        </div>
        <div class="header-actions">
          <el-button @click="refreshData">
            <i class="fas fa-sync-alt mr-2"></i>刷新
          </el-button>
        </div>
      </div>
    </header>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索案件编号、当事人姓名..."
            size="large"
            clearable
          >
            <template #prefix>
              <i class="fas fa-search"></i>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="filters.status" placeholder="归档状态" clearable>
            <el-option label="待归档" value="pending"></el-option>
            <el-option label="审核中" value="reviewing"></el-option>
            <el-option label="已归档" value="archived"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
          </el-select>
          
          <el-select v-model="filters.type" placeholder="案件类型" clearable>
            <el-option label="民事纠纷" value="civil"></el-option>
            <el-option label="劳动争议" value="labor"></el-option>
            <el-option label="合同纠纷" value="contract"></el-option>
            <el-option label="知识产权" value="ip"></el-option>
          </el-select>
          
          <el-select v-model="filters.result" placeholder="案件结果" clearable>
            <el-option label="胜诉" value="win"></el-option>
            <el-option label="败诉" value="lose"></el-option>
            <el-option label="和解" value="settlement"></el-option>
            <el-option label="撤诉" value="withdraw"></el-option>
          </el-select>
          
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="clearFilters">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon pending">
            <i class="fas fa-folder-open"></i>
          </div>
          <div class="stat-content">
            <h3>{{ stats.pending }}</h3>
            <p>待归档</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon reviewing">
            <i class="fas fa-eye"></i>
          </div>
          <div class="stat-content">
            <h3>{{ stats.reviewing }}</h3>
            <p>审核中</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon archived">
            <i class="fas fa-archive"></i>
          </div>
          <div class="stat-content">
            <h3>{{ stats.archived }}</h3>
            <p>已归档</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon rejected">
            <i class="fas fa-times-circle"></i>
          </div>
          <div class="stat-content">
            <h3>{{ stats.rejected }}</h3>
            <p>已拒绝</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 案件列表 -->
    <div class="table-section">
      <div class="table-container">
        <el-table :data="filteredCases" stripe>
          <el-table-column prop="caseNumber" label="案件编号" width="150" fixed="left">
            <template #default="scope">
              <span class="case-number">{{ scope.row.caseNumber }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="title" label="案件标题" min-width="200">
            <template #default="scope">
              <div class="case-title">
                <h4>{{ scope.row.title }}</h4>
                <p class="case-desc">{{ scope.row.description }}</p>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="parties" label="当事人" width="120">
            <template #default="scope">
              <div class="parties-info">
                <span class="name">{{ scope.row.parties }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="type" label="案件类型" width="120">
            <template #default="scope">
              <el-tag :type="getTypeColor(scope.row.type)" size="small">
                {{ getTypeName(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="result" label="案件结果" width="100">
            <template #default="scope">
              <el-tag :type="getResultColor(scope.row.result)" size="small">
                {{ getResultName(scope.row.result) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="归档状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusColor(scope.row.status)" size="small">
                {{ getStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="endTime" label="结案时间" width="160">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.endTime) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="submitTime" label="申请时间" width="160">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.submitTime) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="viewCaseDetail(scope.row)">查看详情</el-button>
              <el-button 
                size="small" 
                type="primary" 
                @click="startReview(scope.row)" 
                v-if="scope.row.status === 'pending'"
              >
                开始审核
              </el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="approveArchive(scope.row)" 
                v-if="scope.row.status === 'reviewing'"
              >
                批准归档
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="rejectArchive(scope.row)" 
                v-if="scope.row.status === 'reviewing'"
              >
                拒绝归档
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="filteredCases.length"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </div>
    </div>

    <!-- 归档详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="归档审批详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="selectedCase" class="case-detail">
        <div class="detail-grid">
          <div class="detail-section">
            <h3>基本信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <label>案件编号：</label>
                <span>{{ selectedCase.caseNumber }}</span>
              </div>
              <div class="info-item">
                <label>案件标题：</label>
                <span>{{ selectedCase.title }}</span>
              </div>
              <div class="info-item">
                <label>当事人：</label>
                <span>{{ selectedCase.parties }}</span>
              </div>
              <div class="info-item">
                <label>案件类型：</label>
                <el-tag :type="getTypeColor(selectedCase.type)" size="small">
                  {{ getTypeName(selectedCase.type) }}
                </el-tag>
              </div>
              <div class="info-item">
                <label>案件结果：</label>
                <el-tag :type="getResultColor(selectedCase.result)" size="small">
                  {{ getResultName(selectedCase.result) }}
                </el-tag>
              </div>
              <div class="info-item">
                <label>结案时间：</label>
                <span>{{ formatDateTime(selectedCase.endTime) }}</span>
              </div>
              <div class="info-item">
                <label>申请时间：</label>
                <span>{{ formatDateTime(selectedCase.submitTime) }}</span>
              </div>
            </div>
          </div>
          
          <div class="detail-section">
            <h3>案件描述</h3>
            <p class="case-description">{{ selectedCase.description }}</p>
          </div>
          
          <div class="detail-section">
            <h3>案件总结</h3>
            <p class="case-summary">{{ selectedCase.summary }}</p>
          </div>
          
          <div class="detail-section">
            <h3>归档材料</h3>
            <div class="file-list">
              <div v-for="file in selectedCase.archiveDocuments" :key="file.id" class="file-item">
                <i class="fas fa-file-alt"></i>
                <span>{{ file.name }}</span>
                <el-button size="small" text @click="downloadFile(file)">下载</el-button>
              </div>
            </div>
          </div>
          
          <div class="detail-section" v-if="selectedCase.status !== 'pending'">
            <h3>审批记录</h3>
            <div class="approval-history">
              <div v-for="record in selectedCase.approvalHistory" :key="record.id" class="history-item">
                <div class="history-header">
                  <span class="reviewer">{{ record.reviewer }}</span>
                  <span class="time">{{ formatDateTime(record.time) }}</span>
                </div>
                <div class="history-content">
                  <el-tag :type="record.action === 'approve' ? 'success' : 'danger'" size="small">
                    {{ record.action === 'approve' ? '批准' : '拒绝' }}
                  </el-tag>
                  <p v-if="record.comment">{{ record.comment }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button 
            type="primary" 
            @click="startReview(selectedCase)" 
            v-if="selectedCase && selectedCase.status === 'pending'"
          >
            开始审核
          </el-button>
          <el-button 
            type="success" 
            @click="approveArchive(selectedCase)" 
            v-if="selectedCase && selectedCase.status === 'reviewing'"
          >
            批准归档
          </el-button>
          <el-button 
            type="danger" 
            @click="rejectArchive(selectedCase)" 
            v-if="selectedCase && selectedCase.status === 'reviewing'"
          >
            拒绝归档
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

export default {
  name: 'ArchiveApproval',
  setup() {
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(20)
    const showDetailDialog = ref(false)
    const selectedCase = ref(null)
    
    const filters = reactive({
      status: '',
      type: '',
      result: ''
    })
    
    const stats = reactive({
      pending: 0,
      reviewing: 0,
      archived: 0,
      rejected: 0
    })
    
    // 模拟案件数据
    const cases = ref([
      {
        id: 1,
        caseNumber: 'GD2024001',
        title: '张三诉李四合同纠纷案',
        description: '因购买商品质量问题产生的合同纠纷案件已结案',
        parties: '张三 vs 李四',
        type: 'contract',
        result: 'win',
        status: 'pending',
        endTime: '2024-01-10 16:30:00',
        submitTime: '2024-01-15 09:30:00',
        summary: '经审理，法院认定被告李四存在违约行为，判决支持原告张三的诉讼请求，要求被告赔偿经济损失50万元。',
        archiveDocuments: [
          { id: 1, name: '判决书.pdf' },
          { id: 2, name: '庭审笔录.pdf' },
          { id: 3, name: '证据清单.pdf' },
          { id: 4, name: '执行材料.pdf' }
        ],
        approvalHistory: []
      },
      {
        id: 2,
        caseNumber: 'GD2024002',
        title: '王五诉赵六劳动争议案',
        description: '劳动争议案件通过调解达成和解',
        parties: '王五 vs 赵六',
        type: 'labor',
        result: 'settlement',
        status: 'reviewing',
        endTime: '2024-01-12 14:20:00',
        submitTime: '2024-01-14 10:15:00',
        summary: '双方在法院调解下达成和解协议，被告同意支付原告拖欠工资及补偿金共计15万元。',
        archiveDocuments: [
          { id: 5, name: '调解书.pdf' },
          { id: 6, name: '和解协议.pdf' },
          { id: 7, name: '庭审记录.pdf' }
        ],
        approvalHistory: [
          {
            id: 1,
            reviewer: '审核员B',
            action: 'start_review',
            time: '2024-01-15 11:00:00',
            comment: '开始审核归档申请'
          }
        ]
      },
      {
        id: 3,
        caseNumber: 'GD2024003',
        title: '某公司知识产权侵权案',
        description: '知识产权侵权案件已归档',
        parties: 'ABC公司 vs XYZ公司',
        type: 'ip',
        result: 'lose',
        status: 'archived',
        endTime: '2024-01-08 15:45:00',
        submitTime: '2024-01-10 08:20:00',
        summary: '经审理，法院认定原告提供的证据不足以证明被告存在侵权行为，驳回原告的诉讼请求。',
        archiveDocuments: [
          { id: 8, name: '判决书.pdf' },
          { id: 9, name: '专利文件.pdf' },
          { id: 10, name: '技术比对报告.pdf' }
        ],
        approvalHistory: [
          {
            id: 1,
            reviewer: '审核员C',
            action: 'start_review',
            time: '2024-01-11 09:00:00',
            comment: '开始审核归档申请'
          },
          {
            id: 2,
            reviewer: '审核员C',
            action: 'approve',
            time: '2024-01-11 14:30:00',
            comment: '材料齐全，批准归档'
          }
        ]
      }
    ])
    
    const filteredCases = computed(() => {
      let result = cases.value
      
      if (searchKeyword.value) {
        result = result.filter(case_ => 
          case_.caseNumber.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
          case_.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
          case_.parties.toLowerCase().includes(searchKeyword.value.toLowerCase())
        )
      }
      
      if (filters.status) {
        result = result.filter(case_ => case_.status === filters.status)
      }
      
      if (filters.type) {
        result = result.filter(case_ => case_.type === filters.type)
      }
      
      if (filters.result) {
        result = result.filter(case_ => case_.result === filters.result)
      }
      
      return result
    })
    
    const refreshData = () => {
      updateStats()
      ElMessage.success('数据已刷新')
    }
    
    const updateStats = () => {
      stats.pending = cases.value.filter(c => c.status === 'pending').length
      stats.reviewing = cases.value.filter(c => c.status === 'reviewing').length
      stats.archived = cases.value.filter(c => c.status === 'archived').length
      stats.rejected = cases.value.filter(c => c.status === 'rejected').length
    }
    
    const applyFilters = () => {
      currentPage.value = 1
      ElMessage.success('筛选条件已应用')
    }
    
    const clearFilters = () => {
      Object.keys(filters).forEach(key => {
        filters[key] = ''
      })
      searchKeyword.value = ''
      currentPage.value = 1
      ElMessage.info('筛选条件已重置')
    }
    
    const viewCaseDetail = (case_) => {
      selectedCase.value = case_
      showDetailDialog.value = true
    }
    
    const startReview = async (case_) => {
      try {
        await ElMessageBox.confirm('确定要开始审核这个归档申请吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        
        case_.status = 'reviewing'
        case_.approvalHistory.push({
          id: Date.now(),
          reviewer: '当前审核员',
          action: 'start_review',
          time: new Date().toISOString(),
          comment: '开始审核归档申请'
        })
        
        updateStats()
        ElMessage.success('已开始审核')
        
        if (showDetailDialog.value) {
          showDetailDialog.value = false
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }
    
    const approveArchive = async (case_) => {
      try {
        const { value: comment } = await ElMessageBox.prompt('请输入审批意见（可选）', '批准归档', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入审批意见'
        })
        
        case_.status = 'archived'
        case_.approvalHistory.push({
          id: Date.now(),
          reviewer: '当前审核员',
          action: 'approve',
          time: new Date().toISOString(),
          comment: comment || '材料齐全，批准归档'
        })
        
        updateStats()
        ElMessage.success('已批准归档')
        
        if (showDetailDialog.value) {
          showDetailDialog.value = false
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }
    
    const rejectArchive = async (case_) => {
      try {
        const { value: reason } = await ElMessageBox.prompt('请输入拒绝原因', '拒绝归档', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入拒绝原因',
          inputValidator: (value) => {
            if (!value || value.trim() === '') {
              return '请输入拒绝原因'
            }
            return true
          }
        })
        
        case_.status = 'rejected'
        case_.approvalHistory.push({
          id: Date.now(),
          reviewer: '当前审核员',
          action: 'reject',
          time: new Date().toISOString(),
          comment: reason
        })
        
        updateStats()
        ElMessage.success('已拒绝归档')
        
        if (showDetailDialog.value) {
          showDetailDialog.value = false
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }
    
    const downloadFile = (file) => {
      ElMessage.info(`下载文件：${file.name}`)
    }
    
    const formatDateTime = (date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    }
    
    const getTypeColor = (type) => {
      const colorMap = {
        civil: '',
        labor: 'success',
        contract: 'warning',
        ip: 'danger'
      }
      return colorMap[type] || ''
    }
    
    const getTypeName = (type) => {
      const nameMap = {
        civil: '民事纠纷',
        labor: '劳动争议',
        contract: '合同纠纷',
        ip: '知识产权'
      }
      return nameMap[type] || type
    }
    
    const getResultColor = (result) => {
      const colorMap = {
        win: 'success',
        lose: 'danger',
        settlement: 'warning',
        withdraw: 'info'
      }
      return colorMap[result] || ''
    }
    
    const getResultName = (result) => {
      const nameMap = {
        win: '胜诉',
        lose: '败诉',
        settlement: '和解',
        withdraw: '撤诉'
      }
      return nameMap[result] || result
    }
    
    const getStatusColor = (status) => {
      const colorMap = {
        pending: 'warning',
        reviewing: 'primary',
        archived: 'success',
        rejected: 'danger'
      }
      return colorMap[status] || ''
    }
    
    const getStatusName = (status) => {
      const nameMap = {
        pending: '待归档',
        reviewing: '审核中',
        archived: '已归档',
        rejected: '已拒绝'
      }
      return nameMap[status] || status
    }
    
    onMounted(() => {
      updateStats()
    })
    
    return {
      searchKeyword,
      currentPage,
      pageSize,
      showDetailDialog,
      selectedCase,
      filters,
      stats,
      cases,
      filteredCases,
      refreshData,
      applyFilters,
      clearFilters,
      viewCaseDetail,
      startReview,
      approveArchive,
      rejectArchive,
      downloadFile,
      formatDateTime,
      getTypeColor,
      getTypeName,
      getResultColor,
      getResultName,
      getStatusColor,
      getStatusName
    }
  }
}
</script>

<style scoped>
.archive-approval {
  padding: 20px;
}

.page-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.page-subtitle {
  color: #6b7280;
  margin: 0;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  flex: 1;
  min-width: 300px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-icon.pending {
  background: #f59e0b;
}

.stat-icon.reviewing {
  background: #3b82f6;
}

.stat-icon.archived {
  background: #10b981;
}

.stat-icon.rejected {
  background: #ef4444;
}

.stat-content h3 {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 4px 0;
  color: #1f2937;
}

.stat-content p {
  color: #6b7280;
  margin: 0;
  font-size: 14px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-container {
  padding: 20px;
}

.case-number {
  font-weight: bold;
  color: #3b82f6;
}

.case-title h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.case-desc {
  margin: 0;
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}

.parties-info .name {
  font-weight: 500;
  color: #1f2937;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
  margin-top: 20px;
}

.case-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #e5e7eb;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item label {
  font-weight: 500;
  color: #6b7280;
  min-width: 80px;
}

.case-description,
.case-summary {
  color: #374151;
  line-height: 1.6;
  margin: 0;
  padding: 12px;
  background: #f9fafb;
  border-radius: 6px;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f9fafb;
  border-radius: 6px;
}

.file-item i {
  color: #6b7280;
}

.approval-history {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  padding: 12px;
  background: #f9fafb;
  border-radius: 6px;
  border-left: 3px solid #3b82f6;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.reviewer {
  font-weight: 500;
  color: #1f2937;
}

.time {
  font-size: 12px;
  color: #6b7280;
}

.history-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.history-content p {
  margin: 0;
  color: #374151;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .archive-approval {
    padding: 12px;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    min-width: auto;
  }
  
  .filter-controls {
    justify-content: center;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
